package com.louis.iread.ui;

import android.os.Build;
import android.content.Context;
import android.os.Bundle;
import android.util.TypedValue;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.louis.iread.R;
import com.louis.iread.adapter.SearchAdapter;
import com.louis.iread.bean.AutoComplete;
import com.louis.iread.bean.SearchResultItem;
import com.louis.iread.bean.Website;
import com.louis.iread.bean.WebsiteMgr;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;
import com.louis.iread.net.HttpUtil;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.AppUtils;
import com.louis.iread.utils.DeviceUtils;
import com.louis.iread.utils.NovelUtil;
import com.louis.iread.utils.ThreadPool;
import com.yarolegovich.lovelydialog.LovelyProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class SearchActivity extends SwipeBackActivity {
    private SearchView mSearchView;
    private ListView mSearchResultListView;
    private TextView mSearchTextView;
    private TextView mTextVewInSearch;
    private ListView mAutoCompleteView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SkinMgr.getInstance().register(this);
        setContentView(R.layout.activity_search);
        //实现沉浸式状态栏
        if (Build.VERSION.SDK_INT >= 19) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        initViews();
        EventBus.getDefault().register(this);
    }

    public void initViews() {
        // Inflate the layout for this fragment
        mSearchView = (SearchView) findViewById(R.id.search_view);
        mSearchTextView = (TextView) findViewById(R.id.search_textview);
        mAutoCompleteView = (ListView) findViewById(R.id.auto_complete);
        mSearchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchNovel();
            }
        });
        this.mSearchResultListView = (ListView) findViewById(R.id.search_list);
        //获取到TextView的ID
        int id = mSearchView.getContext().getResources().getIdentifier("android:id/search_src_text",null,null);
        //获取到TextView的控件
        mTextVewInSearch = (TextView) mSearchView.findViewById(id);
        //设置字体大小为14sp
        mTextVewInSearch.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);//14sp
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchNovel();
//                hideKeyboard();
//                mSearchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(final String newText) {
                String text = mSearchView.getQuery().toString().trim();
                if (text == null || text.isEmpty()) {
                    mAutoCompleteView.setVisibility(View.GONE);
                    clearSearchResult();
                    return false;
                }
                if (text.equals(mCurrentQueryString)) {
                    return false;
                }
                clearSearchResult();
                ThreadPool.getInstance().commit(new Runnable() {
                    @Override
                    public void run() {
                        String userAgent = "ZhuiShuShenQi/3.40[preload=false;locale=zh_CN;clientidbase=android-nvidia]";
                        String url = null;
                        try {
                            url = "http://api.zhuishushenqi.com/book/auto-complete?query=" + URLEncoder.encode(newText, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        Map<String, String> headers = new HashMap<>();
                        headers.put("User-Agent", "ZhuiShuShenQi/3.40[preload=false;locale=zh_CN;clientidbase=android-nvidia]"); // 不能转UTF-8
                        headers.put("X-User-Agent", "ZhuiShuShenQi/3.40[preload=false;locale=zh_CN;clientidbase=android-nvidia]");
                        headers.put("X-Device-Id", DeviceUtils.getIMEI(AppUtils.getAppContext()));
                        headers.put("Host", "api.zhuishushenqi.com");
                        headers.put("Connection", "Keep-Alive");
                        headers.put("If-None-Match", "W/\"2a04-4nguJ+XAaA1yAeFHyxVImg\"");
                        headers.put("If-Modified-Since", "Tue, 02 Aug 2016 03:20:06 UTC");
                        String json = HttpUtil.getStringByOk(url, headers);
                        if (json != null && !json.isEmpty()) {
                            AutoComplete autoComplete = JSON.parseObject(json, AutoComplete.class);
                            if (autoComplete == null || autoComplete.keywords == null || autoComplete.keywords.size() == 0) {
                                return;
                            }
                            EventBus.getDefault().post(new ReadEvent(EventType.AUTO_COMPLETE_RESULT, autoComplete));
                            Log.i("====", json);
                        }
                    }
                });
                return false;
            }
        });

        ImageView backView = (ImageView) findViewById(R.id.back);
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private ArrayAdapter<String> mAutoCompleteAdapter;
    private String mCurrentQueryString = null;
    private void showAutoComplete(View parent, final ArrayList<String> list) {
        mAutoCompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        mAutoCompleteAdapter.addAll(list);
        mAutoCompleteView.setAdapter(mAutoCompleteAdapter);
        mAutoCompleteView.setVisibility(View.VISIBLE);
        mAutoCompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCurrentQueryString = list.get(position);
                mSearchView.setQuery(list.get(position), true);
                mAutoCompleteView.setVisibility(View.GONE);
            }
        });

        mAutoCompleteAdapter.notifyDataSetChanged();
    }

    private SearchAdapter mSearchResultAdapter;

    /**
     * 搜索的网站数目
     */
    private int mSiteNum = 0;

    protected LovelyProgressDialog dialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(ReadEvent event) {
        if (event.getEventType() == EventType.ON_NOVEL_SEARCH) {
            ArrayList<SearchResultItem> searchResultItems = (ArrayList<SearchResultItem>) event.getObj();
            if (mSearchResultAdapter != null) {
                mSearchResultAdapter.addList(searchResultItems);
            }
            else {
                mSearchResultAdapter = new SearchAdapter(SearchActivity.this, R.layout.search_list_item, searchResultItems, com.louis.iread.BR.item);
                mSearchResultListView.setAdapter(mSearchResultAdapter);
            }
        } else if (event.getEventType() == EventType.ON_NOVEL_SEARCH_FIN) {
            dialog.dismiss();
        } else if (event.getEventType() == EventType.AUTO_COMPLETE_RESULT) {
            AutoComplete autoComplete = (AutoComplete) event.getObj();
            showAutoComplete(mSearchView, autoComplete.keywords);
        }
    }

    public void searchNovel() {
        hideKeyboard();
        clearSearchResult();
        mAutoCompleteView.setVisibility(View.GONE);
        mSearchView.clearFocus();
        final String novelName = mSearchView.getQuery().toString();
        if (novelName.trim().isEmpty()) {
            return;
        }
        dialog = new LovelyProgressDialog(this);
        dialog.setIcon(R.drawable.ic_cast_connected_white_36dp)
                .setTitle(R.string.obtain_data)
                .setCancelable(true);
        dialog.show();

        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Website> websites = WebsiteMgr.getManager().getWebsites();
                    ArrayList<SearchResultItem> list = null;
                    for (Website site : websites) {
                        list = NovelUtil.searchNovel(novelName, site);
                        if (list != null && !SearchActivity.this.isDestroyed() && !SearchActivity.this.isFinishing()) {
                            EventBus.getDefault().post(new ReadEvent(EventType.ON_NOVEL_SEARCH, list));
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    EventBus.getDefault().post(new ReadEvent(EventType.ON_NOVEL_SEARCH_FIN));
                }
            }
        });
    }

    private void clearSearchResult() {
        if (mSearchResultAdapter != null) {
            mSearchResultAdapter.clear();
        }
    }

    //退出当前Activity时被调用,调用之后Activity就结束了
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkinMgr.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
        hideKeyboard();
    }

    /*
    隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager == null /*|| !inputMethodManager.isActive()*/) {
            return;
        }

        if (this.getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(mTextVewInSearch.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
    }
}
